package com.yifeng.repo.micro.service.server.engine.conf;

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.config.ConfigService;
import com.yifeng.repo.base.utils.common.BaseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.io.StringReader;
import java.util.Properties;

/**
 * Created by daibing on 2021/11/17.
 */
@Deprecated
public class NacosConf {
    private static final Logger LOGGER = LoggerFactory.getLogger(NacosConf.class);
    private ConfigService configService;
    private String dataId;
    private String group;

    @Resource
    private NacosConfigManager nacosConfigManager;

    public String getConf(String key) {
        String value = this.getConfIfPresent(key);
        if (BaseUtil.isBlank(value)) {
            throw new RuntimeException("Not found conf! Key: " + key);
        }
        return value;
    }

    public String getConfIfPresent(String key) {
        if (configService == null) {
            this.init();
        }
        try {
            // 注意：每次都是全部加载本地配置文件，不建议使用。
            Properties properties = new Properties();
            properties.load(new StringReader(configService.getConfig(dataId, group, 3000)));
            return properties.getProperty(key);
        } catch (Throwable t) {
            LOGGER.warn("nacos conf helper get conf failed: key={}, error=", key, t);
            return null;
        }
    }

    private void init() {
        NacosConfigProperties configProperties = nacosConfigManager.getNacosConfigProperties();
        configService = nacosConfigManager.getConfigService();
        dataId = this.getDataIdPrefix(configProperties) + "." + configProperties.getFileExtension();
        group = configProperties.getGroup();
    }

    private String getDataIdPrefix(NacosConfigProperties configProperties) {
        if (!BaseUtil.isBlank(configProperties.getPrefix())) {
            return configProperties.getPrefix();
        }
        if (!BaseUtil.isBlank(configProperties.getName())) {
            return configProperties.getName();
        }
        return configProperties.getEnvironment().getProperty("spring.application.name");
    }

}
